<?php

namespace App\Service\Message\v1_3_0;

use App\Constants\ErrorCode;
// use App\Helpers\ConfigUtil;
use App\Model\Gift;
use App\Model\GiftLog;
use App\Model\GreetTodayLog;
use App\Model\Message;
use App\Model\Service\ConsumeService;
use App\Model\Setting\SettingAutoMsg;
use App\Model\User;
use App\Model\UserChat;
use App\Model\UserCoin;
use App\Service\BaseService;

/**
 * 今日缘分-打招呼
 */
class SendGreetService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $chatUserIds = $this->request->input('chat_userids', '');
        $greetWords = $this->request->input('greet_words', '');
        //用户ID没有传
        if (!$chatUserIds) return $this->setError(ErrorCode::PARAMETER_ERROR);
        $chatUserIds = explode(',', $chatUserIds);

        $greetType = GreetTodayLog::TYPE_FREE;
        $costCoin = 0;
        $sysGiftId = check_dev_env() ? 22 : 25;
        $giftInfo = Gift::getInfo($sysGiftId);
        //当日已搭讪，非免费
        if (GreetTodayLog::checkCount($userId, date('Y-m-d'))) {
            //打招呼人数
            $greetCoin = $giftInfo['coin']; //ConfigUtil::getGreetMsgCoin();
            $costCoin = count($chatUserIds) * $greetCoin;
            $myCoin = UserCoin::getUserInfo($userId);
            //金币余额
            if ($myCoin['total_coin'] < $costCoin) {
                return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '剩余金币不够打招呼, 可以先充值哦~');
            }
            //扣费
            $chatUserIds = ConsumeService::sendGreetMsg($userId, $chatUserIds, $greetCoin);
            if (empty($chatUserIds)) {
                return $this->setError(ErrorCode::COST_COIN_ERR, '本次扣费异常，请稍后再试～');
            }
            //搭讪记录类型
            $greetType = GreetTodayLog::TYPE_COST;
        }

        //礼物是否要领取
        $giftNeedFetch = true;
        //今日缘分礼物-过期时间（秒）
        $expTime = 7200;
        //添加聊友记录
        foreach ($chatUserIds as $chatUserId) {
            UserChat::addRecord($userId, $chatUserId, UserChat::FROM_QUICK_CHAT);
            //添加送礼记录
            GiftLog::addSysGiftRecord(
                $userId,
                $chatUserId,
                GiftLog::FROM_SUPER_CHAT,
                $giftNeedFetch,
                $giftInfo,
                $expTime
            );
        }

        //批量发送私信
        $imAccounts = User::getImAccounts($chatUserIds);
        $ret['list'] = array_values(array_unique($imAccounts));
        $ret['auto_msgs'] = [
            [
                'msg_type' => 'text',
                'content' => $greetWords,
                'duration' => 0,
            ]
        ];

        //礼物消息
        Message::sendGift($chatUserIds, $userId, $giftInfo, $giftNeedFetch, 1, '打招呼礼物');

        //搭讪记录
        GreetTodayLog::addLog($userId, $chatUserIds, $greetType, $costCoin);
        $ret['cost_coin'] = $costCoin;
        log_user_result($userId, $ret);
        return $ret;
    }
}
